package com.rick.shiro.controller;

import com.rick.shiro.entity.User;
import lombok.extern.java.Log;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/********************************************************
 *@Desc:
 *@Author: ZRP
 *@Date: 2017/12/22 14:38
 ********************************************************/
@Controller
@Log
public class LoginController {

    @RequestMapping("/login")
    public String login() {
        log.info("=================login=================");
        return "login";
    }

    @RequestMapping("/loginUser")
    public String loginUser(String username, String password, HttpSession session) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);   //完成登录
            User user = (User) subject.getPrincipal();
            session.setAttribute("user", user);
            return "index";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "login";//返回登录页面
        }
    }

    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        log.info("msg===" + subject.getPrincipal().toString());
        session.removeAttribute("user");
        subject.logout();

        return "login";
    }

}
